package com.mengxuegu.web.controller;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/**
 * @author william
 * @create 2021-07-01 21:20
 **/
@Controller
public class MainController {
    @RequestMapping({"/index", "/", ""})
    public String indefx(Map<String, Object> map) {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal != null && principal instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) principal;
            map.put("username",userDetails.getUsername());
        }
        return "index";
    }

    /**
     * springSecurity  会更具方法的参数为 Authentication 自动帮我们注入Authentication
     * @param authentication
     * @return
     */
    @RequestMapping("/user/info")
    @ResponseBody
    public Object userInfo(Authentication authentication){

        return authentication.getPrincipal();
    }
    @RequestMapping("/user/info2")
    @ResponseBody
    public Object userInfo2( @AuthenticationPrincipal UserDetails userDetails){
        return userDetails;

    }



}
